<template>
  <div>
    <el-dialog
      width="1024px"
      :close-on-click-modal="false"
      :show-close="true"
      v-bind="$attrs"
      v-on="$listeners"
      @open="onOpen"
      @close="onClose"
    >
      <div slot="title">
        {{ formData.id != null ? '修改发票' : '新增发票' }}
      </div>
      <div class="sketch_content">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="80px"
                 label-position="top"
        >
          <div class="partition-header">
            <div class="partition-mark" style="border-left-color: rgb(75,130,255);"></div>
            <div class="partition-title">基本信息</div>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发票申请编号" prop="invoiceApplySn">
                <el-input v-model="formData.invoiceApplySn" placeholder="根据规则自动生成，支持手动输入"
                          :style="{width: '100%'}"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerName">
                <el-input @click.native="customerIdClick" placeholder="请选择客户" v-model="formData.customerName"
                          style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同编号" prop="contractSn">
                <el-input v-model="formData.contractSn" placeholder="请选择合同" :disabled="formData.customerId == null"
                          prefix-icon="el-icon-mobile" :style="{width: '100%'}" @click.native="contractIdClick"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同金额" prop="contractMoney">
                <el-input v-model="formData.contractMoney" :style="{width: '100%'}" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开票金额" prop="invoiceMoney">
                <el-input v-model="formData.invoiceMoney" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开票日期" prop="invoiceDate">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="formData.invoiceDate" type="datetime"
                                placeholder="请选择" style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开票类型" prop="invoiceType">
                <el-select v-model="formData.invoiceType" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="dict in dict.type.crm_invoice_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" type="textarea" :autosize="{minRows: 3, maxRows: 5}"
                          :style="{width: '100%'}"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="partition-header">
            <div class="partition-mark" style="border-left-color: rgb(75,130,255);"></div>
            <div class="partition-title">发票信息</div>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="抬头类型" prop="titleTypeId">
                <el-select v-model="formData.titleTypeId" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="dict in dict.type.crm_title_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开票抬头" prop="invoiceTitle">
                <el-input v-model="formData.invoiceTitle" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="纳税人识别号" prop="taxNumber">
                <el-input v-model="formData.taxNumber" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户行" prop="depositBank">
                <el-input v-model="formData.depositBank" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开户账号" prop="depositAccount">
                <el-input v-model="formData.depositAccount" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电话" prop="telephone">
                <el-input v-model="formData.telephone" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="开票地址" prop="depositAddress">
                <el-input v-model="formData.depositAddress" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="partition-header">
            <div class="partition-mark" style="border-left-color: rgb(75,130,255);"></div>
            <div class="partition-title">邮寄信息</div>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactsName">
                <el-input v-model="formData.contactsName" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="contactsMobile">
                <el-input v-model="formData.contactsMobile" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮寄地址" prop="contactsAddress">
                <el-input v-model="formData.contactsAddress" placeholder="请选择" :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="详细地址" prop="detailAddress">
                <el-input v-model="formData.detailAddress" type="textarea"
                          placeholder="输入详细地址（XX街道XX路XX号XX大厦XX栋XX楼XX室）"
                          :autosize="{minRows: 3, maxRows: 5}"
                          :style="{width: '100%'}"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitForm" :loading="submitLoading">保 存</el-button>
        <el-button size="small" @click="onClose">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 客户选择 -->
    <customer-select-popover ref="customerSelectPopover" @callback="customerDataCallback"
                             v-if="customerPopoverVisiable"
    />
    <!-- 合同选择 -->
    <contract-select-popover ref="contractSelectPopover" @callback="contractDataCallback"/>
  </div>
</template>
<script>
import {
  saveHasKey,
  selectByPrimaryKey,
  updateByPrimaryKeySelective
} from '@/api/crm/Invoice'

import CustomerSelectPopover from '@/components/Crm/Customer/CustomerSelectPopover'
import ContractSelectPopover from '@/components/Crm/Contract/ContractSelectPopover'

export default {
  inheritAttrs: false,
  components: {
    CustomerSelectPopover,
    ContractSelectPopover
  },
  dicts: ['crm_invoice_type', 'crm_title_type'],
  props: {
    pk: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      submitLoading: false,
      customerPopoverVisiable: false,
      formData: {
        id: undefined,
        invoiceApplySn: undefined,
        customerName: undefined,
        contractSn: undefined,
        money: undefined,
        invoiceMoney: undefined,
        invoiceDate: undefined,
        invoiceType: undefined,
        remark: '正在开票中',
        titleTypeId: undefined,
        invoiceTitle: '江苏贵友有限公司',
        taxNumber: '12359468745',
        depositBank: '贵友开发银行',
        depositAccount: '13456123123123123',
        telephone: '0500123648',
        depositAddress: '江苏贵友东路1号',
        contactsName: '高琪',
        contactsMobile: '123123456789',
        contactsAddress: '江苏贵友东路1号',
        detailAddress: '贵友大厦北栋18层031室'
      },
      rules: {
        customerName: [{ required: true, message: '请选择客户', trigger: ['blur', 'change'] }],
        contractSn: [{ required: true, message: '请选择合同', trigger: ['blur', 'change'] }],
        invoiceMoney: [{ required: true, message: '请输入开票金额', trigger: 'blur' }],
        invoiceType: [{ required: true, message: '请选择开票类型', trigger: 'blur' }],
        titleTypeId: [{ required: true, message: '请选择抬头类型', trigger: 'blur' }]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {
  },
  methods: {
    onOpen() {
      if (this.pk != null) {
        selectByPrimaryKey(this.pk).then(res => {
          this.formData = res.data
          console.log('显示数据', this.formData)
        })
      }
    },
    onClose() {
      this.$refs['elForm'].resetFields()
      this.$emit('update:visible', false)
    },
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          if (this.formData.id != undefined) {
            // 修改
            updateByPrimaryKeySelective(this.formData).then(res => {
              this.$modal.msgSuccess('修改成功')
              this.$emit('ok')
              this.onClose()
            })
          } else {
            // 新增
            saveHasKey(this.formData).then(res => {
              this.$modal.msgSuccess('添加成功')
              this.$emit('ok')
              this.onClose()
            })
          }
        }
      })
    },
    // 客户input点击事件
    customerIdClick() {
      this.customerPopoverVisiable = true
      this.$nextTick(() => {
        this.$refs.customerSelectPopover.open()
      })
    },
    // 客户弹出框回调
    customerDataCallback(data) {
      // 如果旧id不等于新id，则证明客户变更了，需要重置商机和客户签约人
      if (this.formData.customerId != data.id) {
        this.formData.contractSn = null
        this.formData.contractName = ''
        this.formData.contractId = null
      }
      this.formData.customerId = data.id
      this.formData.customerName = data.customerName
    },
    // 合同input点击事件
    contractIdClick() {
      if (this.formData.customerId != null) {
        this.$nextTick(() => {
          this.$refs.contractSelectPopover.open('invoice', this.formData.customerId)
        })
      }
    },
    // 合同弹出框回调
    contractDataCallback(data) {
      this.formData.contractId = data.id
      this.formData.contractSn = data.contractSn
      this.formData.contractName = data.contractName
      this.formData.money = data.money
      this.formData.invoiceMoney = data.money
    }
  }
}

</script>
<style>
</style>
